//
//  MyCLController.m
//  Hermes
//
//  Created by Martin Verzilli on 9/24/08.
//  Copyright 2008 Manas Technology Solutions SRL. All rights reserved.
//

#import "MyCLController.h"

@implementation MyCLController

@synthesize currentLocation, locationManager;

- (void) timerFired:(NSTimer*)userInfo {
	[locationManager stopUpdatingLocation];
	if (currentLocation != nil) {
		[delegate locationUpdate: currentLocation];	
	}
}

- (id) initWithDelegate: (id<MyCLControllerDelegate>) dlg {
	self = [super init];
	if (self != nil) {
		delegate = dlg;
		currentLocation = nil;
		locationManager = [[CLLocationManager alloc] init];
		locationManager.delegate = self; // Tells the location manager to send updates to this object
		locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	}
	return self;
}

- (void) refreshLocationWaiting:(NSTimeInterval) seconds {
	[NSTimer scheduledTimerWithTimeInterval: seconds 
									 target: self
								   selector: @selector(timerFired:)
								   userInfo: nil
									repeats: NO];
	
	[self.locationManager startUpdatingLocation];
}

// Called when the location is updated
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{
	if ( signbit(newLocation.horizontalAccuracy) ) // Fall negative, cannot obtain location
	{
		[self fireError:@"Could not obtain the location"];
		return;
	} 
		
	if ( newLocation != nil )
	{
		if (currentLocation == nil || (currentLocation.horizontalAccuracy >= newLocation.horizontalAccuracy && abs(newLocation.timestamp.timeIntervalSinceNow) < 10 ))    
		{
			[currentLocation release];			
			currentLocation = [newLocation retain];
		}	
	}
}

- (void) fireError:(NSString *)msg {
	if (currentLocation != nil)
		[currentLocation release];
	currentLocation = nil;
	[delegate locationError: msg];
}

// Called when there is an error getting the location
- (void)locationManager:(CLLocationManager *)manager
	   didFailWithError:(NSError *)error
{
	[self fireError:[error description]];
}

- (void) dealloc {
	[locationManager release];
	[currentLocation release];
	[super dealloc];
}

@end